<?php

namespace App\Console\Commands;

use App\Models\CouponReceiveModel;
use App\Models\WxActionLogModel;
use App\Repositories\DinnerLogRepository;
use App\Services\Task\TaskBusinessControlOperate;
use Illuminate\Console\Command;

class WxCouponConsumeStatusUpdate extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wx:coupon:consume:status:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '微信代金券消费状态更新';


    private static $taskBusinessType = 1;
    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->perHandle();

        return true;
    }

    /**
     * 每次执行处理，简陋实现秒级定时任务
     * @return true
     */
    public function perHandle() {
        $nowTime = time();
        $perTime = 55; //每次预定执行的时间
        $maxNum = 6; //最大循环数
        $step = 10; //每次步长，秒
        for($i = 0; $i < $maxNum; $i++) {
            //更新代金券核销状态
            $this->updateConsumeStatus();
            //判断时间是否已经超出一分钟
            if((time() - $nowTime) >= $perTime) {
                break;
            }
            sleep($step); //每次步长
        }

        return true;
    }

    /**
     * 更新代金券核销状态
     * @return array|true
     */
    public function updateConsumeStatus() {
        #获取执行时间范围及起始id
        $timeRes = TaskBusinessControlOperate::getLogAndStart([
            'taskBusinessType' => self::$taskBusinessType,
            'nowTime'          => time() - 3, //当前时间，时间锚点
            'timeoutMax'       => 60, //超时时间
            'stepTime'         => 30, //每次执行时间步长
        ]);
        if (!empty($timeRes['skip'])) { //未到超时时间，跳过该次执行
            return [];
        }
        $taskStartDate = $timeRes['taskStartDate'];
        $taskEndDate = $timeRes['taskEndDate'];
//        //测试用时间
//        $taskStartDate = '2024-02-20 10:05:10';
//        $taskEndDate = '2024-02-20 10:06:00';
        //获取回调信息列表
        $page = 1;
        //阻塞进程 循环分页读取时间范围内所有数据
        $num = 0;
        $sucNum = 0;
        while (true) {
            $dataRes = \App\Services\Common\HttpClientEasy::clientGet('https://api-supermarket-csaf.lxi.cloud/wx/common/coupon/callbacklograngelist', [], [
                'start_date' => $taskStartDate,
                'end_date'   => $taskEndDate,
                'page'       => $page,
                'page_size'  => 1000,
            ]);
            if($dataRes['code'] != 0 || !$dataRes['data']) {
                break;
            }
            $data = $dataRes['data'];
            foreach($data['list'] as $k => $val) {
                $num++;
                //验证核销状态，非已核销状态不处理
                if($val['status'] != 'USED') {
                    continue;
                }
                $couponId = $val['coupon_id'] ?? 0; //核销的上架id
                $consumeMchid = $val['consume_information']['consume_mchid'] ?? 0; //核销的上架id
                if(!$couponId || !$consumeMchid) {
                    continue;
                }
                //根据券批次id和券id定位具体代金券
                $couponRes = CouponReceiveModel::query()
                    ->where('stock_id', $val['stock_id'])
                    ->where('coupon_id', $val['coupon_id'])
                    ->where('consume_status', 1)
                    ->first();
                if(!$couponRes) {
                    continue;
                }
                //更新代金券核销状态
                // 插入用餐记录表
                $dinnerLog = new DinnerLogRepository();
                $dinnerLogRes = $dinnerLog->addByCoupon($val['coupon_id'], $consumeMchid);
                //更新核销状态
                $consumeRes = \App\Services\CouponService::updateConsumeStatusByCouponId($val['coupon_id'], 2);
                if (!$consumeRes['errcode']) {
                    $acLogStatus = 1;
                }
                $sucNum++;
                //记录微信动作日志
                $acLogDesc = ($acLogStatus == 1 && $dinnerLogRes) ? '成功' : '失败';
                $saveData = [
                    'event'    => 'coupon_consume',
                    'event_id' => $val['coupon_id'],
                    'desc'     => "用户核销消费券，{$acLogDesc}",
                    'data'     => json_encode([
                        'message'         => $val,
                    ]),
                    'status'   => $acLogStatus,
                ];
                WxActionLogModel::query()
                    ->insert($saveData);
            }
            //循环至最后一页跳出
            if($data['totalPage'] <= $data['currentPage']) {
                break;
            }
            $page++;
        }
        //更新计划任务控制
        TaskBusinessControlOperate::finish([
            'taskBusinessType' => self::$taskBusinessType,
            'taskStartDate'    => $taskStartDate,
            'taskEndDate'      => $taskEndDate,
        ]);

        echo "本次处理{$num}条，成功{$sucNum}条\r\n";

        return true;
    }

}